from django import template
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe
from django.contrib.sites.models import Site

register = template.Library()

from django.conf import settings

FACEBOOK_API_KEY = getattr(settings, 'FACEBOOK_API_KEY', None)
FACEBOOK_SECRET_KEY = getattr(settings, 'FACEBOOK_SECRET_KEY', None)
FACEBOOK_RECEIVER_FILE = getattr(settings, 'FACEBOOK_RECEIVER_FILE', None)
LOGIN_REDIRECT_URL = getattr(settings, 'LOGIN_REDIRECT_URL', None)


connect_script = """
<script type="text/javascript"> 
FB_RequireFeatures(["XFBML"], function() { 
    FB.Facebook.init("%(facebook_api_key)s", "%(facebook_receiver_file)s"); 
    $(document.getElementsByTagName('fb:login-button')).bind('click',function(e){
        e.preventDefault();
        fb_registration();
    });
        
}); 
function fb_registration(){
    FB.Facebook.get_sessionState().waitUntilReady(function() { 
        api = FB.Facebook.apiClient;
        sess = api.get_session();
        api.users_getInfo(sess.uid,['first_name',
            'last_name',
            'birthday',
            'profile_update_time',
        ],function(e){ 
            ret = e[0];
            $.post('%(post_url)s'+sess.uid+'/',{
                'session_key':sess.session_key,
                'uid':sess.uid,
                'secret':sess.secret,
                'sig':sess.sig,
                'expires':parseInt(sess.expires),
                'first_name':ret.first_name,
                'last_name':ret.last_name,
                'birthday':ret.birthday,
                'profile_update_time':ret.profile_update_time,
            },function(e){
                userform_refresh(e);
            }, 'json');
        });            
    }); 
}
function userform_setup(){
    $(document).ready(function(){
        $('#username_form').ajaxForm({
            dataType: 'json',
            success: userform_refresh
        });
    });
}
function userform_refresh(data){
    if (data.form){
        $.facebox(data.form);
        userform_setup();
    }
    else if(data.redirect_to && !data.form){
        document.location = data.redirect_to;
    }
    else if (!data.redirect_to && !data.form && data.message ){
        $.facebox(data.message);
    }else if (data.errors){
        $.facebox(data.errors);
    }
}
</script> 
""" % {'facebook_api_key':FACEBOOK_API_KEY,
    'facebook_receiver_file': FACEBOOK_RECEIVER_FILE,
    'redirect':LOGIN_REDIRECT_URL,
    'post_url':reverse('fbconnect_login_plain', args = [])}

def fb_featureLoaderScript(parser, token):
    """ 
    Template tag to insert the facebook connect feature loader script 
    {% load fbconnect_tags %}
    {% fb_feature_loader_script %}
    """

    return FBFeatureLoaderScript()

class FBFeatureLoaderScript(template.Node):
    def __init__(self):
        pass

    def render(self, context):
        return mark_safe('<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"></script>')


def fb_connectScript(parser, token):
    """
    Template tag to insert the facebook connect login script
    {% load fbconnect_tags %}
    {% fb_connect_script %}
    """
    return FBConnectScript()

class FBConnectScript(template.Node):
    def __init__(self):
        pass

    def render(self, context):
        return mark_safe(connect_script)

register.tag('fb_feature_loader_script', fb_featureLoaderScript)
register.tag('fb_connect_script', fb_connectScript)

